package com.example.demo.security;

import com.example.demo.model.SysRole;
import com.example.demo.model.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class UserDetailsImpl implements UserDetails {
    private User user;

    private List<String> roles;
    public UserDetailsImpl(){

    }
    public UserDetailsImpl(User user)
    {
        this.user=user;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList=new ArrayList<>();
        for(SysRole role : user.getSysRoles())
        {
            authorityList.add(new SimpleGrantedAuthority((role.getName())));
        }
        return authorityList;
    }


    public List<String> getRoles() {
        roles=new ArrayList<>();

        for(GrantedAuthority s : getAuthorities())
        {
            roles.add(s.getAuthority());
        }
        return  roles;
    }

    @Override
    @JsonIgnore
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}